package org.example.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.example.dao.DBUtil;



public class Main {
    public void handleMessage(String message) throws SQLException {
        if (message.startsWith("data:image")){
            // 图片数据
            saveImageToDatabase(message);
        } else  {
            // JSON 格式的文本消息
            chat(message);
        }
    }

    public void chat(String message) throws SQLException {
        Pattern pattern = Pattern.compile("\"sender\":\"(.*?)\"");
        Matcher matcher = pattern.matcher(message);
        Pattern patternm = Pattern.compile("\"receiver\":\"(.*?)\"");
        Matcher matcherm = patternm.matcher(message);
        Pattern patternme = Pattern.compile("\"message_content\":\"(.*?)\"");
        Matcher matcherme = patternme.matcher(message);
        int sender = 0;
        if (matcher.find()) {
            String senderStr = matcher.group(1); // 提取匹配的字符串
            try {
                sender = Integer.parseInt(senderStr); // 将字符串转换为整数
            } catch (NumberFormatException e) {
                System.out.println("无法将匹配的字符串转换为整数。");
                e.printStackTrace();
            }
        }
        int receiver = 0;
        if (matcherm.find()) {
            String receiverStr = matcherm.group(1); // 提取匹配的字符串
            try {
                receiver = Integer.parseInt(receiverStr); // 将字符串转换为整数
            } catch (NumberFormatException e) {
                System.out.println("无法将匹配的字符串转换为整数。");
                e.printStackTrace();
            }
        }
        String message_content = "";
        if (matcherme.find()) {
            message_content = matcherme.group(1);
        }

        // SQL 插入语句
        String sql = "INSERT INTO chat_record (Sender_id, receiver_id, message_content)VALUES (?, ?, ?);";

        // 使用 DBUtil 的 executePreparedUpdate 方法插入数据
        int result = DBUtil.executePreparedUpdate(sql, sender, receiver, message_content);

        // 根据操作结果进行相应处理
        if (result > 0) {
            System.out.println("消息已成功保存到数据库");
        } else {
            System.out.println("保存消息失败");
        }
    }

    public void saveImageToDatabase(String message) {
        Pattern patternSender = Pattern.compile("\"sender\":\"(\\d+)\"");
        Matcher matcherSender = patternSender.matcher(message);
        Pattern patternReceiver = Pattern.compile("\"receiver\":\"(\\d+)\"");
        Matcher matcherReceiver = patternReceiver.matcher(message);
        Pattern patternMessageContent = Pattern.compile("\"data\":\\[\"(.*?)\"\\]");
        Matcher matcherMessageContent = patternMessageContent.matcher(message);

        int sender = 0;
        if (matcherSender.find()) {
            String senderStr = matcherSender.group(1); // 提取匹配的字符串
            try {
                sender = Integer.parseInt(senderStr); // 将字符串转换为整数
            } catch (NumberFormatException e) {
                System.out.println("无法将匹配的字符串转换为整数： " + senderStr);
                e.printStackTrace();
            }
        }

        int receiver = 0;
        if (matcherReceiver.find()) {
            String receiverStr = matcherReceiver.group(1); // 提取匹配的字符串
            try {
                receiver = Integer.parseInt(receiverStr); // 将字符串转换为整数
            } catch (NumberFormatException e) {
                System.out.println("无法将匹配的字符串转换为整数： " + receiverStr);
                e.printStackTrace();
            }
        }

        String messageContent = "";
        if (matcherMessageContent.find()) {
            messageContent = matcherMessageContent.group(1);
        }

        // SQL 插入语句
        String sql = "INSERT INTO chat_record (Sender_id, receiver_id, message_content) VALUES (?, ?, ?);";

        try (PreparedStatement pstmt = DBUtil.getConn().prepareStatement(sql)) {
            // 设置参数
            pstmt.setInt(1, sender);
            pstmt.setInt(2, receiver);
            pstmt.setString(3, messageContent);

            // 执行插入操作
            int result = pstmt.executeUpdate();

            // 根据操作结果进行相应处理
            if (result > 0) {
                System.out.println("图片路径已成功保存到数据库");
            } else {
                System.out.println("保存图片路径到数据库失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("保存图片路径到数据库失败：" + e.getMessage());
        }

    }
    public void updateLastRecordReceiver(int newReceiverId) {
        // 查询最后一条数据
        String selectLastRecordSQL = "SELECT * FROM chat_record ORDER BY message_id DESC LIMIT 1";

        try (PreparedStatement selectStmt = DBUtil.getConn().prepareStatement(selectLastRecordSQL)) {
            ResultSet resultSet = selectStmt.executeQuery();

            // 检查是否有结果
            if (resultSet.next()) {
                // 获取最后一条数据的相关字段值
                int messageId = resultSet.getInt("message_id"); // 假设 id 是消息的唯一标识

                // 构建更新 receiver 的 SQL 语句
                String updateReceiverSQL = "UPDATE chat_record SET receiver_id = ? WHERE message_id = ?";

                try (PreparedStatement updateStmt = DBUtil.getConn().prepareStatement(updateReceiverSQL)) {
                    // 设置参数
                    updateStmt.setInt(1, newReceiverId);
                    updateStmt.setInt(2, messageId);

                    // 执行更新操作
                    int rowsUpdated = updateStmt.executeUpdate();

                    // 根据更新结果进行相应处理
                    if (rowsUpdated > 0) {
                        System.out.println("最后一条数据的 receiver 已成功更新为：" + newReceiverId);
                    } else {
                        System.out.println("更新最后一条数据的 receiver 失败");
                    }
                }
            } else {
                System.out.println("没有找到最后一条数据");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("更新最后一条数据的 receiver 时出现 SQL 异常：" + e.getMessage());
        }
    }
    public List<Integer> getLoggedInUserIds() {
        List<Integer> userIds = new ArrayList<>();
        String sql = "SELECT user_id FROM user WHERE login_status != 0";

        try (Connection conn = DBUtil.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                int userId = rs.getInt("user_id");
                userIds.add(userId);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("获取已登录用户时出现 SQL 异常：" + e.getMessage());
        }

        return userIds;
    }
    public void updateLastRecordReceiverBasedOnPrevious() {
        // 查询最后一条数据和倒数第二条数据
        String selectLastTwoRecordsSQL = "SELECT * FROM chat_record ORDER BY message_id DESC LIMIT 2";

        try (PreparedStatement selectStmt = DBUtil.getConn().prepareStatement(selectLastTwoRecordsSQL)) {
            ResultSet resultSet = selectStmt.executeQuery();

            // 检查是否有两条结果
            if (resultSet.next()) {
                // 获取最后一条数据的相关字段值
                int lastMessageId = resultSet.getInt("message_id");
                int lastSenderId = resultSet.getInt("sender_id");

                if (resultSet.next()) {
                    // 获取倒数第二条数据的相关字段值
                    int previousSenderId = resultSet.getInt("sender_id");
                    int previousReceiverId = resultSet.getInt("receiver_id");

                    // 比较最后一条和倒数第二条的发送方
                    if (lastSenderId == previousSenderId) {
                        // 构建更新最后一条数据的接收方的 SQL 语句
                        String updateReceiverSQL = "UPDATE chat_record SET receiver_id = ? WHERE message_id = ?";

                        try (PreparedStatement updateStmt = DBUtil.getConn().prepareStatement(updateReceiverSQL)) {
                            // 设置参数
                            updateStmt.setInt(1, previousReceiverId);
                            updateStmt.setInt(2, lastMessageId);

                            // 执行更新操作
                            int rowsUpdated = updateStmt.executeUpdate();

                            // 根据更新结果进行相应处理
                            if (rowsUpdated > 0) {
                                System.out.println("最后一条数据的 receiver 已成功更新为：" + previousReceiverId);
                            } else {
                                System.out.println("更新最后一条数据的 receiver 失败");
                            }
                        }
                    } else {
                        System.out.println("最后一条数据和倒数第二条数据的发送方不同，未进行更新。");
                    }
                } else {
                    // 只有一条数据，不进行更新
                    System.out.println("只有一条数据，不进行更新。");
                }
            } else {
                System.out.println("没有找到最后一条数据");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("更新最后一条数据的 receiver 时出现 SQL 异常：" + e.getMessage());
        }
    }
}
